package edu.biwu.request;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/req/upload01")
@MultipartConfig //该注解专门用于处理文件上传，需要Servlet 3.0及以上版本
public class RequestUpload01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.通过request对象获取一个Part接口，Part中封装了上传文件的所有信息
        Part uploadFile = request.getPart("uploadFile");

        //2.获取上传的文件相关信息
        /*System.out.println(uploadFile.getSubmittedFileName()); //上传的文件名 xxx.xx
        System.out.println(uploadFile.getContentType());//该文件的MIME类型
        System.out.println(uploadFile.getSize());//该文件的大小，单位是字节*/
        String fileName = uploadFile.getSubmittedFileName();

        String extension = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID() + extension;

        //3.将上传的文件写入到服务端的某个位置，
        File file = new File("D:/uploadFile");
        if (!file.exists()){
            file.mkdir();
        }

        //4.将上传的文件写入到服务端的某个位置上，存储上传文件
        uploadFile.write(file + "/" + newFileName);//直接上传文件写入指定位置

        //5.上传成功，响应上传成功提示
        response.setContentType("text/html;charset=UTF-8");//防止响应中文乱码
        response.getWriter().write(fileName + "上传成功");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
